// Fill out your copyright notice in the Description page of Project Settings.


#include "ST_SimpleScreenshot.h"
#include "Engine/GameViewportClient.h"
#include "Kismet/GameplayStatics.h"
#include "Engine/World.h"
#include "EngineUtils.h"
#include "GameFramework/PlayerController.h"

AST_SimpleScreenshot* AST_SimpleScreenshot::GetSimpleScreenshot(UObject* WorldContextObject)
{
	if (!GEngine) {
		return nullptr;
	}
	UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull);
	if (!World) {
		return nullptr;
	}

	for (TActorIterator<AST_SimpleScreenshot> It(World, AST_SimpleScreenshot::StaticClass()); It; ++It)
	{
		AST_SimpleScreenshot* Actor = *It;
		if (IsValid(Actor)) {
			return Actor;
		}
	}


	AST_SimpleScreenshot* outActor = World->SpawnActor<AST_SimpleScreenshot>();
	outActor->InitSimpleScreenshot();
	return outActor;
}



// Sets default values
AST_SimpleScreenshot::AST_SimpleScreenshot()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = false;
	isInShot = false;
}

void AST_SimpleScreenshot::InitSimpleScreenshot() {

}


void AST_SimpleScreenshot::OnShotCallBack(int32 Width, int32 Height, const TArray<FColor>& Colors)
{
	shotWidth = Width;
	shotHeight = Height;
	backColors = Colors;
	UGameViewportClient::OnScreenshotCaptured().RemoveAll(this);

	if (onSimpleScreenshotCaptured.IsBound()) 
	{
		onSimpleScreenshotCaptured.Broadcast(Width, Height, backColors);
	}
	isInShot = false;
}



bool AST_SimpleScreenshot::HightShotNow(int multiple)
{
	if (isInShot)
	{
		return false;
	}
	multiple = FMath::Clamp(multiple, 1, 4);
	APlayerController* cp = UGameplayStatics::GetPlayerController(this,0);
	if (cp) {
		UGameViewportClient::OnScreenshotCaptured().AddUObject(this, &AST_SimpleScreenshot::OnShotCallBack);
		FString cmd = "HighResShot "+FString::FromInt(multiple);
		isInShot = true;
		cp->ConsoleCommand(cmd);
		return true;
	}

	return false;
}

void AST_SimpleScreenshot::BeginDestroy() 
{
	UGameViewportClient::OnScreenshotCaptured().RemoveAll(this);
	isInShot = false;
	Super::BeginDestroy();
}

// Called when the game starts or when spawned
void AST_SimpleScreenshot::BeginPlay()
{
	Super::BeginPlay();
	//UGameViewportClient::OnScreenshotCaptured();
	//FScreenshotRequest::OnScreenshotCaptured();
}

// Called every frame
void AST_SimpleScreenshot::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

}

